package com.spancer.usercenter.util;

import com.google.common.collect.Maps;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author masisi
 * @date 2022/11/14 11:28
 * @Description 相同类中属性值比较工具类
 */
public class CompareObjectUtil {

    public static Map<String,String> compareFieldOfObject(Object oldObject, Object newObject, List<String> filterFieldList) throws InstantiationException, IllegalAccessException {
        if (oldObject!=null && newObject!=null) {
            List<Field> fieldList = Arrays.asList(oldObject.getClass().getDeclaredFields());
            fieldList.stream()
                    .filter(x-> (CollectionUtils.isEmpty(filterFieldList))?true:filterFieldList.contains(x.getName()))
                    .forEachOrdered(field ->{
                        try {
                            field.setAccessible(true);
                            Object oldV = field.get(oldObject);
                            Object newV = field.get(newObject);
                            if (!oldV.equals(newV)) {
                                System.out.println("change:oldV:" + oldV + ",newV:" + newV);
                            } else {
                                System.out.println("no change:oldV:" + oldV + ",newV:" + newV);
                            }
                        } catch (IllegalAccessException e) {
                            throw new RuntimeException(e);
                        }
                    });
        }
        return Maps.newConcurrentMap();
    }

}
